package com.shizhanzhe.zxbapp.vip;

import android.app.Activity;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.gyf.barlibrary.ImmersionBar;
import com.shizhanzhe.zxbapp.R;
import com.shizhanzhe.zxbapp.bean.PDDDetail;
import com.shizhanzhe.zxbapp.bean.PDDURL;
import com.shizhanzhe.zxbapp.bean.UserBean;
import com.shizhanzhe.zxbapp.ui.BindingPhoneActivity;
import com.shizhanzhe.zxbapp.url.Path;
import com.shizhanzhe.zxbapp.utils.OkHttpDownloadJsonUtil;
import com.shizhanzhe.zxbapp.utils.Util;
import com.shizhanzhe.zxbapp.widget.ShareWxPopupWindow;
import com.shizhanzhe.zxbapp.widget.SignDialog;

import org.w3c.dom.Text;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.wechat.friends.Wechat;
import cn.sharesdk.wechat.moments.WechatMoments;

/**
 * Created by zz9527 on 2018/12/17.
 */
public class PDDDetailActivity extends Activity {
    private PDDDetail pddDetail;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pdddetail);
        ImmersionBar.with(this).statusBarColor(R.color.them).fitsSystemWindows(true)
                .init();
        findViewById(R.id.backarea).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        final ImageView img = findViewById(R.id.img);
        final TextView title = findViewById(R.id.tv_title);
        final TextView qhprice = findViewById(R.id.tv_quan_hou_price);
        final TextView nowprice = findViewById(R.id.tv_price_on_line);
        final TextView sell = findViewById(R.id.tv_sell_count);
        final TextView time = findViewById(R.id.time);
        final TextView qprice = findViewById(R.id.tv_quan_price);
        final TextView yongjin = findViewById(R.id.yongjin);
        final TextView tv_share = findViewById(R.id.tv_share);
        final LinearLayout buy = findViewById(R.id.buy);
        final TextView tv = findViewById(R.id.tv);
        RecyclerView recycler = findViewById(R.id.recycler);
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.HORIZONTAL);
        recycler.setLayoutManager(manager);
        final PDDRelatedAdapter mRelatedAdapter = new PDDRelatedAdapter(this);
        recycler.setAdapter(mRelatedAdapter);
        OkHttpDownloadJsonUtil.downloadJson(this, Path.PDDDETAIL(getIntent().getStringExtra("goods_id")), new OkHttpDownloadJsonUtil.onOkHttpDownloadListener() {
            @Override
            public void onsendJson(String json) {
                try {
                    Gson gson = new Gson();
                    pddDetail = gson.fromJson(json, PDDDetail.class);
                    Glide.with(PDDDetailActivity.this).load(pddDetail.getData().getGoods_gallery_urls().get(0)).apply(new RequestOptions().error(R.mipmap.logo)).into(img);
                    title.setText(pddDetail.getData().getGoods_name());
                    double price = pddDetail.getData().getMin_group_price() / 100;
                    double price2 = ((double) pddDetail.getData().getMin_group_price() - (double) pddDetail.getData().getCoupon_discount()) / 100;
                    String yj = Util.Sub(price2 * ((double) pddDetail.getData().getPromotion_rate() / 1000) * (Double.parseDouble(UserBean.divide) + Double.parseDouble(UserBean.vipdivide)) + "");
                    qhprice.setText(" " + price2 + "元");
                    nowprice.setText("原价:" + price + "元");
                    sell.setText("月销量:" + pddDetail.getData().getSold_quantity());
                    yongjin.setText("¥ " + yj);
                    tv_share.setText("¥ " + yj);
                    if (pddDetail.getData().getCoupon_discount() != 0) {
                        qprice.setText((double) pddDetail.getData().getCoupon_discount() / 100 + "元优惠券");
                        time.setText("使用期限:" + getDateTimeFromMillisecond(pddDetail.getData().getCoupon_start_time()) + "-" + getDateTimeFromMillisecond(pddDetail.getData().getCoupon_end_time()));
                    } else {
                        buy.setVisibility(View.GONE);
                        nowprice.setText("");
                        tv.setText("优惠价");
                    }


                    List<PDDDetail.ListBean> list = pddDetail.getList();
                    mRelatedAdapter.updateData(list);
                    mRelatedAdapter.setListener(new PDDRelatedAdapter.PDDSourceListener() {
                        @Override
                        public void click(PDDDetail.ListBean item) {
                            startActivity(new Intent(PDDDetailActivity.this, PDDDetailActivity.class).putExtra("goods_id", item.getGoods_id()));
                        }
                    });
                } catch (Exception e) {
                    setResult(120);
                    Toast.makeText(PDDDetailActivity.this, "商品已下架", Toast.LENGTH_SHORT).show();
                    finish();
                }
            }
        });


        OkHttpDownloadJsonUtil.downloadJson(this, Path.PDDURL(UserBean.uid, getIntent().getStringExtra("goods_id")), new OkHttpDownloadJsonUtil.onOkHttpDownloadListener() {
            @Override
            public void onsendJson(String json) {
                Gson gson = new Gson();
                try {
                    pddurl = gson.fromJson(json, PDDURL.class);
                } catch (Exception e) {

                } finally {
                    findViewById(R.id.buy).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if ("".equals(UserBean.mobile)) {
                                final SignDialog dialog = new SignDialog(PDDDetailActivity.this);
                                dialog.setListener(new SignDialog.SignListener() {
                                    @Override
                                    public void checktrue() {
                                        startActivityForResult(new Intent(PDDDetailActivity.this, BindingPhoneActivity.class),1);
                                        dialog.dismiss();
                                    }
                                });
                                dialog.show();
                                dialog.showBD("未绑定手机", "绑定后即可使用此功能");
                                return;
                            }
                            Intent intent = new Intent();
                            intent.setAction("android.intent.action.VIEW");
                            Uri content_url = Uri.parse(pddurl.getData().getMobile_short_url());
                            intent.setData(content_url);
                            startActivity(intent);
                        }
                    });
                    findViewById(R.id.buybar).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if ("".equals(UserBean.mobile)) {
                                final SignDialog dialog = new SignDialog(PDDDetailActivity.this);
                                dialog.setListener(new SignDialog.SignListener() {
                                    @Override
                                    public void checktrue() {
                                        startActivityForResult(new Intent(PDDDetailActivity.this, BindingPhoneActivity.class),1);
                                        dialog.dismiss();
                                    }
                                });
                                dialog.show();
                                dialog.showBD("未绑定手机", "绑定后即可使用此功能");

                                return;
                            }
                            Intent intent = new Intent();
                            intent.setAction("android.intent.action.VIEW");
                            Uri content_url = Uri.parse(pddurl.getData().getMobile_short_url());
                            intent.setData(content_url);
                            startActivity(intent);
                        }
                    });
                    findViewById(R.id.share).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if ("".equals(UserBean.mobile)) {
                                final SignDialog dialog = new SignDialog(PDDDetailActivity.this);
                                dialog.setListener(new SignDialog.SignListener() {
                                    @Override
                                    public void checktrue() {
                                        startActivityForResult(new Intent(PDDDetailActivity.this, BindingPhoneActivity.class),1);
                                        dialog.dismiss();
                                    }
                                });
                                dialog.show();
                                dialog.showBD("未绑定手机", "绑定后即可使用此功能");
                                return;
                            }
                            final ShareWxPopupWindow wxPopupWindow = new ShareWxPopupWindow(PDDDetailActivity.this);
                            wxPopupWindow.setWxListener(new ShareWxPopupWindow.ShareWxListener() {
                                @Override
                                public void shareFriend() {
                                    wxPopupWindow.dismiss();
                                    Wechat.ShareParams sp = new Wechat.ShareParams();
                                    sp.setTitle(pddDetail.getData().getGoods_name());
                                    sp.setText(pddDetail.getData().getGoods_desc());
                                    sp.setUrl(pddurl.getData().getWe_app_web_view_short_url());
                                    sp.setImageUrl(pddDetail.getData().getGoods_image_url());
                                    sp.setShareType(Platform.SHARE_WEBPAGE);
                                    Platform weChat = ShareSDK.getPlatform(Wechat.NAME);
                                    weChat.share(sp);
                                }

                                @Override
                                public void shareCircle() {
                                    wxPopupWindow.dismiss();
                                    WechatMoments.ShareParams sp = new WechatMoments.ShareParams();
                                    sp.setTitle(pddDetail.getData().getGoods_name());
                                    sp.setUrl(pddurl.getData().getWe_app_web_view_short_url());
//                        sp.setImageUrl(Path.BASE_URL+Arrays.asList(bean.getImg().substring(1, bean.getImg().length()).split(",")).get(0));
                                    sp.setShareType(Platform.SHARE_WEBPAGE);
                                    Platform Moments = ShareSDK.getPlatform(WechatMoments.NAME);
                                    Moments.share(sp);
                                }

                                @Override
                                public void shareSave() {
                                }
                            });
                            wxPopupWindow.showDown2(sell);

                        }
                    });
                }
            }
        });
    }
    PDDURL pddurl;
    @Override
    protected void onDestroy() {
        super.onDestroy();
        ImmersionBar.with(this).destroy();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode==100){
            Log.i("_____-","100");
            OkHttpDownloadJsonUtil.downloadJson(this, Path.PDDURL(UserBean.uid, getIntent().getStringExtra("goods_id")), new OkHttpDownloadJsonUtil.onOkHttpDownloadListener() {
                @Override
                public void onsendJson(String json) {
                    Log.i("_____-",json);
                    try {
                        Gson gson = new Gson();
                        pddurl = gson.fromJson(json, PDDURL.class);
                    }catch (Exception e){
                        Log.i("_____-",e.toString());
                    }

                }
            });
        }
    }

    /**
     * 将毫秒转化成固定格式的时间
     * 时间格式: yyyy-MM-dd HH:mm:ss
     *
     * @param millisecond
     * @return
     */
    public static String getDateTimeFromMillisecond(long millisecond) {
        System.setProperty("user.timezone", "Asia/Shanghai");
        TimeZone tz = TimeZone.getTimeZone("Asia/Shanghai");
        TimeZone.setDefault(tz);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date(millisecond * 1000);
        String dateStr = simpleDateFormat.format(date);
        return dateStr;
    }
}
